package com.ruoyi.business.service.impl;

import com.ruoyi.business.domain.EquipmentTypes;
import com.ruoyi.business.domain.EquipmentVariables;
import com.ruoyi.business.mapper.EquipmentTypesMapper;
import com.ruoyi.business.mapper.EquipmentVariablesMapper;
import com.ruoyi.business.service.IEquipmentVariablesService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 存储设备变量参数信息的Service业务层处理
 * 
 * @author ldkj
 * @date 2025-02-27
 */
@Service
public class EquipmentVariablesServiceImpl implements IEquipmentVariablesService 
{
    @Autowired
    private EquipmentVariablesMapper equipmentVariablesMapper;

    @Autowired
    private EquipmentTypesMapper equipmentTypesMapper;


    /**
     * 查询存储设备变量参数信息的
     * 
     * @param variableId 存储设备变量参数信息的主键
     * @return 存储设备变量参数信息的
     */
    @Override
    public EquipmentVariables selectEquipmentVariablesByVariableId(Long variableId)
    {
        return equipmentVariablesMapper.selectEquipmentVariablesByVariableId(variableId);
    }

    /**
     * 查询存储设备变量参数信息的列表
     * 
     * @param equipmentVariables 存储设备变量参数信息的
     * @return 存储设备变量参数信息的
     */
    @Override
    public List<EquipmentVariables> selectEquipmentVariablesList(EquipmentVariables equipmentVariables)
    {
        return equipmentVariablesMapper.selectEquipmentVariablesList(equipmentVariables);
    }

    /**
     * 新增存储设备变量参数信息的
     * 
     * @param equipmentVariables 存储设备变量参数信息的
     * @return 结果
     */
    @Override
    public int insertEquipmentVariables(EquipmentVariables equipmentVariables)
    {
        return equipmentVariablesMapper.insertEquipmentVariables(equipmentVariables);
    }

    /**
     * 修改存储设备变量参数信息的
     * 
     * @param equipmentVariables 存储设备变量参数信息的
     * @return 结果
     */
    @Override
    public int updateEquipmentVariables(EquipmentVariables equipmentVariables)
    {

        return equipmentVariablesMapper.updateEquipmentVariables(equipmentVariables);
    }

    /**
     * 批量删除存储设备变量参数信息的
     * 
     * @param variableIds 需要删除的存储设备变量参数信息的主键
     * @return 结果
     */
    @Override
    public int deleteEquipmentVariablesByVariableIds(Long[] variableIds)
    {
        return equipmentVariablesMapper.deleteEquipmentVariablesByVariableIds(variableIds);
    }

    /**
     * 删除存储设备变量参数信息的信息
     * 
     * @param variableId 存储设备变量参数信息的主键
     * @return 结果
     */
    @Override
    public int deleteEquipmentVariablesByVariableId(Long variableId)
    {
        return equipmentVariablesMapper.deleteEquipmentVariablesByVariableId(variableId);
    }





    /**
     * 导入设备变量数据
     * 
     * @param equipmentVariablesList 设备变量数据列表
     * @param isUpdateSupport 是否更新支持，如果已存在，是否进行更新数据
     * @param operName 操作用户
     * @return 结果
     */
    @Override
    public String importEquipmentVariables(List<EquipmentVariables> equipmentVariablesList, Boolean isUpdateSupport, String operName)
    {
        if (equipmentVariablesList == null || equipmentVariablesList.size() == 0)
        {
            throw new RuntimeException("导入设备变量数据不能为空！");
        }
        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();
        
        for (EquipmentVariables equipmentVariables : equipmentVariablesList)
        {
            try
            {
                // 验证必填字段
                if (equipmentVariables.getVariableName() == null || equipmentVariables.getVariableName().trim().isEmpty())
                {
                    failureNum++;
                    failureMsg.append("<br/>" + failureNum + "、变量名称不能为空");
                    continue;
                }
                
                if (equipmentVariables.getVariableEnName() == null || equipmentVariables.getVariableEnName().trim().isEmpty())
                {
                    failureNum++;
                    failureMsg.append("<br/>" + failureNum + "、英文变量名称不能为空");
                    continue;
                }
                
                // 处理次级设备类型名称到ID的转换
                if (equipmentVariables.getSecondaryEquipmentTypeName() != null && !equipmentVariables.getSecondaryEquipmentTypeName().trim().isEmpty())
                {
                    // 根据次级设备类型名称查找对应的ID
                    EquipmentTypes typeQuery = new EquipmentTypes();
                    typeQuery.setEquipmentTypeName(equipmentVariables.getSecondaryEquipmentTypeName().trim());
                    List<EquipmentTypes> typeList = equipmentTypesMapper.selectEquipmentTypesList(typeQuery);
                    
                    if (typeList.size() > 0)
                    {
                        equipmentVariables.setSecondaryEquipmentTypeId(typeList.get(0).getEquipmentTypeId());
                    }
                    else
                    {
                        failureNum++;
                        failureMsg.append("<br/>" + failureNum + "、变量 " + equipmentVariables.getVariableName() + " 的次级设备类型 '" + equipmentVariables.getSecondaryEquipmentTypeName() + "' 不存在");
                        continue;
                    }
                }
                

                
                // 验证是否存在这个组合唯一键（父类设备名称 + 变量名称 + 英文变量名称）
                String secondaryEquipmentTypeName = equipmentVariables.getSecondaryEquipmentTypeName() != null ? 
                    equipmentVariables.getSecondaryEquipmentTypeName().trim() : "";
                String variableName = equipmentVariables.getVariableName().trim();
                String variableEnName = equipmentVariables.getVariableEnName().trim();
                
                EquipmentVariables existingVariable = equipmentVariablesMapper.selectEquipmentVariablesByUniqueKey(
                    secondaryEquipmentTypeName, variableName, variableEnName);
                
                if (existingVariable == null)
                {
                    // 不存在，新增
                    // 清空ID，让数据库自动生成
                    equipmentVariables.setVariableId(null);
                    equipmentVariablesMapper.insertEquipmentVariables(equipmentVariables);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、变量 [" + secondaryEquipmentTypeName + "-" + 
                        variableName + "-" + variableEnName + "] 导入成功");
                }
                else if (isUpdateSupport)
                {
                    // 存在且支持更新，更新数据
                    equipmentVariables.setVariableId(existingVariable.getVariableId());
                    equipmentVariablesMapper.updateEquipmentVariables(equipmentVariables);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、变量 [" + secondaryEquipmentTypeName + "-" + 
                        variableName + "-" + variableEnName + "] 更新成功");
                }
                else
                {
                    // 存在且不支持更新，跳过（不计入失败）
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、变量 [" + secondaryEquipmentTypeName + "-" + 
                        variableName + "-" + variableEnName + "] 已存在，跳过");
                }
            }
            catch (Exception e)
            {
                failureNum++;
                String variableName = equipmentVariables != null && equipmentVariables.getVariableName() != null ? 
                    equipmentVariables.getVariableName() : "未知变量";
                String msg = "<br/>" + failureNum + "、变量 " + variableName + " 导入失败：";
                failureMsg.append(msg + e.getMessage());
            }
        }
        if (failureNum > 0)
        {
            if (successNum > 0)
            {
                return "导入完成！成功 " + successNum + " 条，失败 " + failureNum + " 条。" + 
                       "成功信息：" + successMsg.toString() + "失败信息：" + failureMsg.toString();
            }
            else
            {
                failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
                throw new RuntimeException(failureMsg.toString());
            }
        }
        else
        {
            successMsg.insert(0, "恭喜您，数据已全部导入完成！共 " + successNum + " 条，数据如下：");
        }
        return successMsg.toString();
    }

    /**
     * 查询设备变量列表（用于导出，包含次级设备类型名称）
     * 确保所有设备类型都被包含在导出中，即使某些设备类型没有对应的变量数据
     * 
     * @param equipmentVariables 设备变量
     * @return 设备变量集合
     */
    @Override
    public List<EquipmentVariables> selectEquipmentVariablesListForExport(EquipmentVariables equipmentVariables)
    {
        // 1. 查询现有的设备变量数据
        List<EquipmentVariables> existingVariables = equipmentVariablesMapper.selectEquipmentVariablesList(equipmentVariables);
        
        // 2. 获取所有设备类型
        List<EquipmentTypes> allEquipmentTypes = equipmentTypesMapper.selectEquipmentTypesList(new EquipmentTypes());
        
        // 3. 创建结果列表
        List<EquipmentVariables> resultList = new ArrayList<>();
        
        // 4. 填充现有变量的设备类型名称，并收集已有设备类型ID
        List<Long> existingEquipmentTypeIds = new ArrayList<>();
        for (EquipmentVariables item : existingVariables)
        {
            if (item.getSecondaryEquipmentTypeId() != null)
            {
                existingEquipmentTypeIds.add(item.getSecondaryEquipmentTypeId());
                EquipmentTypes equipmentType = equipmentTypesMapper.selectEquipmentTypesByEquipmentTypeId(item.getSecondaryEquipmentTypeId());
                if (equipmentType != null)
                {
                    item.setSecondaryEquipmentTypeName(equipmentType.getEquipmentTypeName());
                }
            }
            resultList.add(item);
        }
        
        // 5. 为没有变量数据的设备类型创建空记录
        for (EquipmentTypes equipmentType : allEquipmentTypes)
        {
            // 检查这个设备类型是否已经在现有变量中存在
            if (!existingEquipmentTypeIds.contains(equipmentType.getEquipmentTypeId()))
            {
                // 创建一个只包含设备类型信息的空变量记录
                EquipmentVariables emptyVariable = new EquipmentVariables();
                emptyVariable.setSecondaryEquipmentTypeId(equipmentType.getEquipmentTypeId());
                emptyVariable.setSecondaryEquipmentTypeName(equipmentType.getEquipmentTypeName());
                emptyVariable.setVariableName(""); // 设为空字符串而不是null，便于Excel显示
                emptyVariable.setVariableEnName("");
                emptyVariable.setArea("");
                emptyVariable.setValueSource("");
                emptyVariable.setVariableValue("");
                emptyVariable.setDescription("");
                emptyVariable.setUnit("");
                
                resultList.add(emptyVariable);
            }
        }
        
        return resultList;
    }

    /**
     * 根据变量英文名称列表批量查询设备变量
     *
     * @param variableEnNames 变量英文名称列表
     * @return 设备变量集合
     */
    @Override
    public List<EquipmentVariables> selectEquipmentVariablesByEnNames(List<String> variableEnNames) {
        if (variableEnNames == null || variableEnNames.isEmpty()) {
            return new ArrayList<>();
        }
        return equipmentVariablesMapper.selectEquipmentVariablesByEnNames(variableEnNames);
    }

    /**
     * 批量更新设备变量的值和更新时间
     *
     * @param equipmentVariables 设备变量列表
     * @return 影响的行数
     */
    @Override
    public int batchUpdateVariableValues(List<EquipmentVariables> equipmentVariables) {
        if (equipmentVariables == null || equipmentVariables.isEmpty()) {
            return 0;
        }
        return equipmentVariablesMapper.batchUpdateVariableValues(equipmentVariables);
    }

}
